const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
const parseTime = (time, cFormat)=> {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

const deepClone = (source)=> {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const richHtml = str => {
  return str
    .replace(/(&.+?;)/g, (matched)=> {
      let rs = asciiChartSet_en2c[matched];
      return rs == undefined ? '' : rs;
    })
    .replace(/\<img/gi, '<img style="max-width:100%;height:auto" ')
    // .replace(/\<img/gi, '<img class="rich-img" ');
}

const asciiChartSet_en2c = {
  '&nbsp;': ' ',
  '&excl;': '!',
  '&quot;': '"',
  '&num;': '#',
  '&dollar;': '$',
  '&percnt;': '%',
  '&amp;': '&',
  '&apos;': '\'',
  '&lpar;': '(',
  '&rpar;': ')',
  '&ast;': '*',
  '&plus;': '+',
  '&comma;': ',',
  '&hyphen;': '-',
  '&period;': '.',
  '&sol;': '/',
  '&colon;': ':',
  '&semi;': ';',
  '&lt;': '<',
  '&equals;': '=',
  '&gt;': '>',
  '&quest;': '?',
  '&commat;': '@',
  '&lsqb;': '[',
  '&bsol;': '\\',
  '&rsqb;': ']',
  '&circ;': '^',
  '&lowbar;': '_',
  '&grave;': '`',
  '&lcub;': '{',
  '&verbar;': '|',
  '&rcub;': '}',
  '&tilde;': '~',
}

module.exports = {
  parseTime,
  formatTime,
  richHtml,
  deepClone
}
